package com.syezon.wifikey.news.data;

import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.crypto.Cipher;


/**
 *
 *
 */
public class HttpUtils {
    private static final String TAG = HttpUtils.class.getSimpleName();

    private static final String BASE_URL1 = "http://stw";
    private static final String BASE_URL2 = "ifi.ho";
    private static final String BASE_URL3 = "danet.com";

    private static final String CDN_BASE_URL1 = "http://cdn-stw";
    private static final String CDN_BASE_URL2 = "ifi.ho";
    private static final String CDN_BASE_URL3 = "danet.com";

    private static final String DEFAULT_DOMAIN = "971D8A6080BA50411CDEFF83B95DAAAABA42F043BF05E100A80C9B9D0F0AE917";
    private static final String DEFAULT_CDN_DOMAIN = "31652FDBB4B2E1D8DD8DBA7968719FA212B4A365A8F1DDCB2CDB7F5409D79DA0";
    public static final String KEY = "abcdefghijk123456";

    public static String getTTNews = "https://www.ttdailynews.com/api/list.htm?cid=571122&category=1&page=";

    /**
     * 发送HTTP POST请求，获取服务器返回的接口数据（带参数）
     *
     * @param url
     * @return
     */
    public static String getResponse(String url) throws IOException {
        // 创建HTTP连接
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET"); // 使用POST请求，默认GET
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        // 进行连接，提交参数，并获取返回的数据
        String result = "";
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream(); // 获取输入流，此时才真正建立链接
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bufferReader = new BufferedReader(isr);
            String line = "";
            while ((line = bufferReader.readLine()) != null) {
                result += line + "\n";
            }
            if (bufferReader != null) {
                bufferReader.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (is != null) {
                is.close();
            }
            return result;
        } else {
            return "";
        }
    }

    /**
     * 发送HTTP get请求，获取服务器返回的接口数据（带参数）
     *
     * @param url
     * @param param
     * @return
     */

    public static String getResult(String url, String param, int type) throws IOException {
        // 创建HTTP连接
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
//            conn.setDoInput(true); // 允许输入流，即允许下载，默认为true
//            conn.setDoOutput(true); // Post请求需要允许输出流，即允许上传，默认为false
//            conn.setUseCaches(false); //  Post请求不能使用缓存
        // conn.setRequestMethod("GET"); // 使用POST请求，默认GET
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        // 设置请求参数
        //     byte[] data = param.getBytes("UTF-8");
        //      OutputStream os = conn.getOutputStream();
        //       os.write(data);
        //     os.flush();
        //     os.close();
        // 进行连接，提交参数，并获取返回的数据
        String result = "";

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream(); // 获取输入流，此时才真正建立链接
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bufferReader = new BufferedReader(isr);
            String line = "";
            while ((line = bufferReader.readLine()) != null) {
                result += line + "\n";
            }
            if (bufferReader != null) {
                bufferReader.close();
            }
            if (bufferReader != null) {
                isr.close();
            }
            if (bufferReader != null) {
                is.close();
            }
            return result;
        } else {
        }
        return "";
    }

    /**
     * 发送HTTP POST请求，获取服务器返回的接口数据（带参数）
     *
     * @param url
     * @param param
     * @return
     */
    public static String getResult(String url, String param) throws IOException {
        // 创建HTTP连接
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setDoInput(true); // 允许输入流，即允许下载，默认为true
        conn.setDoOutput(true); // Post请求需要允许输出流，即允许上传，默认为false
        conn.setUseCaches(false); //  Post请求不能使用缓存
        conn.setRequestMethod("POST"); // 使用POST请求，默认GET
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        // 设置请求参数
        byte[] data = param.getBytes("UTF-8");
        OutputStream os = conn.getOutputStream();
        os.write(data);
        os.flush();
        os.close();
        // 进行连接，提交参数，并获取返回的数据
        String result = "";
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream(); // 获取输入流，此时才真正建立链接
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bufferReader = new BufferedReader(isr);
            String line = "";
            while ((line = bufferReader.readLine()) != null) {
                result += line + "\n";
            }
            if (bufferReader != null) {
                bufferReader.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (is != null) {
                is.close();
            }
            return result;
        } else {
        }
        return "";
    }


    public static String getBaseUrl() {
        String domain = new StringBuilder().append(BASE_URL1)
                .append(BASE_URL2)
                .append(BASE_URL3).toString();
        try {
            String decodeDomain = AESUtils.aes(DEFAULT_DOMAIN, KEY, Cipher.DECRYPT_MODE);
            if (!TextUtils.isEmpty(decodeDomain)) {
                domain = decodeDomain;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return domain;
    }

    public static String getCdnBaseUrl() {
        String domain = new StringBuilder().append(CDN_BASE_URL1)
                .append(CDN_BASE_URL2)
                .append(CDN_BASE_URL3).toString();
        try {
            String decodeDomain = AESUtils.aes(DEFAULT_CDN_DOMAIN, KEY, Cipher.DECRYPT_MODE);
            if (!TextUtils.isEmpty(decodeDomain)) {
                domain = decodeDomain;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return domain;
    }

    /**
     * 获得上网新闻推广
     *
     * @return
     */
    public static String requestNewsRecommend() throws IOException {
        return getResult(getBaseUrl() + "/doc/static/news_adv.html", "", 0);
    }

    public static String requestDynamicNewsRecommend() throws IOException {
        return getResult(getCdnBaseUrl() + "/doc/news_adv.htm", "", 0);
    }

    /**
     * 获得为您推荐
     *
     * @return
     */
    public static String requestHotRecommend() throws IOException {
        return getResult(getBaseUrl() + "/doc/static/hotRecommend_adv2.html", "", 0);
    }

    public static String requestCompanionNews(String url) throws IOException {
        return getResponse(url);
    }

    /**
     * 从淘宝接口获取城市信息
     *
     * @return
     */
    public static String requestCityFromTaobao() throws IOException {
        String res = getIpFromTaobao("http://ip.taobao.com/service/getIpInfo2.php?ip=myip", "");
        return res;
    }

    public static String getIpFromTaobao(String url, String param) throws IOException {
        // 创建HTTP连接
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("Content-Type", "text/html");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows 7)");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        String result = "";
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream(); // 获取输入流，此时才真正建立链接
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bufferReader = new BufferedReader(isr);
            String line = "";
            while ((line = bufferReader.readLine()) != null) {
                result += line + "\n";
            }
            if (bufferReader != null) {
                bufferReader.close();
            }
            if (bufferReader != null) {
                isr.close();
            }
            if (bufferReader != null) {
                is.close();
            }
            return result;
        } else {
        }
        return "";
    }

    /**
     * 检查获取的数据是否正确
     *
     * @param result
     * @return
     */
    public static boolean checkResult(String result) {
        if (result == null || result.equals("")) {
            return false;
        }
        try {
            JSONObject json = new JSONObject(result);
            if (json.optInt("RC") == 1 || json.optInt("rc") == 1) {
                return true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }
}
